package com.springbootdemo.demo.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.springbootdemo.demo.bean.Brand;
import com.springbootdemo.demo.bean.BrandExample;
import com.springbootdemo.demo.bean.PictureInfo;
import com.springbootdemo.demo.mapper.BrandMapper;
import com.springbootdemo.demo.mapper.PictureInfoMapper;
import com.springbootdemo.demo.utils.FtpClientUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.*;

/**
 * 这是一个demo
 */
@Controller
@RequestMapping("uploads")
public class DemoController {

    private final static Logger logger = LoggerFactory.getLogger(DemoController.class);


   @Autowired
   private Environment environment;



    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private PictureInfoMapper pictureInfoMapper;

    @RequestMapping("demo")
    @ResponseBody
    public Brand getBrandById(){

        logger.info("查询成功！");

        return brandMapper.selectByPrimaryKey(Long.parseLong("1"));
    }

    /**
     * 如果文件在static文件夹下面，return的时候需要加后缀名
     * @return
     */
    @RequestMapping("helloHtml")
    public String toHtml(){
        return "hello.html";
    }


    /**
     * 如果文件在templates文件夹下面，return的时候不需要加后缀名
     * @return
     */
    @RequestMapping("hello2")
    public String hello2(){
        return "hello2";
    }


    /**
     * 分页插件
     */
    @RequestMapping("getByPage")
    @ResponseBody
    public PageInfo<Brand> getByPage(){
        PageHelper.startPage(1, 10);
        BrandExample brandExample = new BrandExample();
        List<Brand> brandList = brandMapper.selectByExample(brandExample);
        PageInfo<Brand> brandPageInfo = new PageInfo<>(brandList);
        System.out.println(brandPageInfo);
        return brandPageInfo;
    }


    @Async("taskExecutor")
    @RequestMapping("hahahha")
    @ResponseBody
    public void updateTimePoint(Date timePointFSR) {

        new Thread(() -> System.out.println("6666")).start();
    }


    @RequestMapping("goToIndex")
    public String goToIndex(){
        return "index";
    }


    //@RequestMapping("upload1")
    @ResponseBody
    public Map<String, String> upload1(@RequestParam("file") MultipartFile file) throws Exception {
        logger.info("[文件类型] - [{}]", file.getContentType());
        logger.info("[文件名称] - [{}]", file.getOriginalFilename());
        logger.info("[文件大小] - [{}]", file.getSize());
        // TODO 将文件写入到指定目录（具体开发中有可能是将文件写入到云存储/或者指定目录通过 Nginx 进行 gzip 压缩和反向代理，此处只是为了演示故将地址写成本地电脑指定目录）
        //上传到本地：
        file.transferTo(new File("E:\\\\1.jpg"));
        Map<String, String> result = new HashMap<>(16);
        result.put("contentType", file.getContentType());
        result.put("fileName", file.getOriginalFilename());
        result.put("fileSize", file.getSize() + "");
        return result;
    }


    /**
     * 上传到linux服务器
     * 上传成功之后，可以直接访问
     * 需要在linux的tomcat中配置，在host标签中加入Context标签，其余不变，
     * 在context标签中，docBase是存放文件的物理路径，我的存放在根目录下的upload文件夹，将他映射成符合http协议的path路径，
     * 重启tomcat
     * 浏览器输入http://192.168.25.129:8080/picture/f1c0ab52-9745-4411-bc5e-f7568f08247b.png即可
     * <Host name="localhost"  appBase="webapps"
     *
     *  <Context docBase="/upload" path="/picture" debug="0" reloadable="true"/>
     * </Host>
     *
     *
     * @return
     */
    @RequestMapping("upload1")
    @ResponseBody
    public PictureInfo uploadToLinux(@RequestParam("file") MultipartFile multipartFile) throws Exception {

        //文件名
        String originalFilename = multipartFile.getOriginalFilename();
        String last = StringUtils.substringAfterLast(originalFilename, ".");
        String uuid = UUID.randomUUID().toString();
        String newName = uuid + "." + last;

        String linux_host_name = environment.getProperty("linux_host_name");
        Integer linux_port = Integer.valueOf(environment.getProperty("linux_port"));
        String linux_username = environment.getProperty("linux_username");
        String linux_password = environment.getProperty("linux_password");
        String pic_path = environment.getProperty("pic_path");
        FtpClientUtils.uploadFile(linux_host_name,
                                  linux_port,
                                  linux_username,
                                  linux_password,
                                  pic_path,
                                  newName,
                                  multipartFile.getInputStream());

        //http://192.168.25.129:8080/picture/f295e47b-706b-4054-bea0-3a80b2c5066e.png

        PictureInfo pictureInfo = new PictureInfo();
        pictureInfo.setId(UUID.randomUUID().toString());
        pictureInfo.setSavePath(linux_host_name + ":8080" + "/picture/" + newName);
        pictureInfoMapper.insert(pictureInfo);
        return pictureInfo;
    }
}
